# flask网页对话程序， 调用zhipuAI库client.chat.completition，
# 用户在网页底部从input栏输入一个问题, 点击提交，使用glm-4-flash模型输出一个回答补全对话，
# 将问题和回答都显示在网页上，循环问答，直到用户输入/quit。
from flask import Flask, render_template, request
from zhipuai import ZhipuAI

app = Flask(__name__)

api_key = "a567d89b7d4f40eea9ae11316558a49e.qqLYnJSsBDYmfIW2"

client = ZhipuAI(api_key=api_key)

model_name = "glm-4-flash"
history = []

@app.route('/', methods=['GET','POST'])
def index():
    if request.method == 'POST':
        question = request.form['question']
        if question.lower() == '/quit':
            history.append({"role": "user", "content": question})
            return render_template('index_app5.html', history=history)
        else:
            response = client.chat.completions.create(
                model=model_name,
                messages=[
                    {"role": "user", "content": question}
                ]
            )
            answer = response.choices[0].message.content
            history.append({"role": "user", "content": question})
            history.append({"role": "assistant", "content": answer})
            return render_template('index_app5.html', history=history)
    else:
        return render_template('index_app5.html', history=history)

if __name__ == '__main__':
    app.run(debug=True)

            
